import { definePageConfig, useRequest } from 'ice';
import { Button, Dialog, Message, Table } from '@alifd/next';
import { useMemo, useRef, useState } from 'react';
import UploadCard, { UploadCardRef } from '@/pages/home/index/components/uploadCard';
import { delById, myImages, PagingInfo } from '@/services/images';
import { baseURL } from '@/config/backendUrl';
import { downloadFile } from '@/utils/image';
import { ColumnProps } from '@alifd/next/types/table';
import OperationMenu from '@/components/operationMenu';
import ManipulationMenu, { FormItemType } from '@/components/manipulationMenu';
import ZPagination from '@/components/ZPagination';

export const pageConfig = definePageConfig(() => {
  return {
    title: '我的图片',
    auth: ['admin'],
  };
});

export default function IndexPage() {
  const [pagingInfo, setPagingInfo] = useState<PagingInfo>({
    take: 20,
    skip: 1,
  });
  const [name, setName] = useState<string | undefined>(undefined);
  // 上传弹窗显示隐藏
  const [dialogShow, setDialogShow] = useState(false);
  // 上传组件实例
  const uploadCardRef = useRef<UploadCardRef>(null);
  // 获取自己的图片 接口
  const myImagesRequest = useRequest(myImages);
  // 筛选
  const handleSubmit = (values: any, errors: any) => {
    if (!errors) {
      setName(values.name);
      myImagesRequest.run({
        ...pagingInfo,
        skip: 1,
      }, values.name);
    }
  };
  // 重置数据
  const ResetData = () => {
    setName(undefined);
    setPagingInfo({
      take: 20,
      skip: 1,
    });
  };
  // 表格
  const { ColumnItem } = useMemo(() => {
    // 删除图片
    const del = (record: any) => {
      delById(record.id).then((data) => {
        if (data.data) {
          Message.success(`${record.name}删除成功`);
          ResetData();
        }
      });
    };

    const ColumnItem: Array<ColumnProps & FormItemType> = [
      {
        title: '编号',
        dataIndex: 'id',
        width: 60,
        align: 'center',
      },
      {
        title: '图片',
        dataIndex: 'url',
        width: 100,
        cell: (value) => {
          return (<img
            src={baseURL + value}
            className="w-full max-w-100"
            alt=""
            onClick={() => {
              Dialog.show({
                content: <img src={baseURL + value} alt="" className="max-h-400px cursor-pointer" />,
                footer: false,
              });
            }}
          />);
        },
      },
      {
        title: '名称',
        dataIndex: 'name',
        placeholder: '请输入要搜索的文件名称',
        isSelect: true,
      },
      {
        title: '上传时间',
        dataIndex: 'createdAt',
        width: 150,
        align: 'center',
        cell: value => new Date(value).toLocaleString(),
      },
      {
        lock: 'right',
        width: 90,
        align: 'center',
        cell: (_value, _index, record) => (<OperationMenu data={[{
          click: () => downloadFile(baseURL + record.url, record.name),
          children: <Button text type="primary">下载</Button>,
        }, {
          click: () => del(record),
          children: <Button text style={{ color: 'red' }}>删除</Button>,
        }]}
        />),
      },
    ];
    return { ColumnItem };
  }, []);
  return (<div className="h-full flex flex-col">
    {/* 表头 */}
    <ManipulationMenu
      title="我的图片"
      ColumnItem={ColumnItem}
      onSubmitClick={handleSubmit}
      onResetClick={ResetData}
      customBtn={(<Button type="primary" onClick={() => setDialogShow(true)}>上传</Button>)}
    />
    <div>
      {/* 表格 */}
      <Table.StickyLock
        style={{ background: 'white' }}
        loading={myImagesRequest.loading}
        dataSource={myImagesRequest.data?.data?.results ?? []}
        fixedHeader
        maxBodyHeight={'calc(100vh - 380px)'}
      >
        {ColumnItem.map((item) => {
          return (<Table.Column {...item} />);
        })}
      </Table.StickyLock>
      {/* 页码 */}
      <ZPagination
        pagingInfo={pagingInfo}
        setPagingInfo={setPagingInfo}
        total={myImagesRequest.data?.data?.total}
        onChange={(pagingInfo) => myImagesRequest.run(pagingInfo, name)}
      />
    </div>
    {/* 弹窗 */}
    <Dialog
      v2
      title="上传图片"
      width={490}
      visible={dialogShow}
      okProps={{ children: '上传' }}
      onClose={() => setDialogShow(false)}
      onOk={() => uploadCardRef.current?.uploadOK()}
      cancelProps={{ children: '完成' }}
    >
      <UploadCard onUpdate={ResetData} ref={uploadCardRef} />
    </Dialog>
  </div>);
}
